﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using kwzx.Data;
using kwzx.Common;

namespace kwzx
{
    public partial class fk : Form
    {
        DataSet1TableAdapters.K_DeviceIssueTableAdapter k_deviceIssue = new DataSet1TableAdapters.K_DeviceIssueTableAdapter();
        DataSet1TableAdapters.T_BMTableAdapter bm = new DataSet1TableAdapters.T_BMTableAdapter();
        DataSet1TableAdapters.T_GROUPTableAdapter group = new DataSet1TableAdapters.T_GROUPTableAdapter();
        DataSet1TableAdapters.CD_CardTypeTableAdapter cd_card = new DataSet1TableAdapters.CD_CardTypeTableAdapter();
        DataSet1TableAdapters.K_CardTableAdapter k_card = new DataSet1TableAdapters.K_CardTableAdapter();
        SPMTableAdapters.TB_USER_CUSTOMINFOTableAdapter tb_user = new SPMTableAdapters.TB_USER_CUSTOMINFOTableAdapter();
        SPMTableAdapters.TB_USER_CARDTableAdapter tb_user_card = new SPMTableAdapters.TB_USER_CARDTableAdapter();
        DataSet1TableAdapters.K_CarddataTableAdapter kcad = new DataSet1TableAdapters.K_CarddataTableAdapter();

        DataSet2TableAdapters.M_user_accgrpTableAdapter useraccg = new DataSet2TableAdapters.M_user_accgrpTableAdapter();

        string fkbk = "";
        int k_gs_id = 0;
        public fk(string fkbk1)
        {
            fkbk = fkbk1;
            InitializeComponent();
        }

        private void fk_Load(object sender, EventArgs e)
        {
            cd_card.Fill(dataSet1.CD_CardType);
            DataTable group_tb = group.GetDataBy_sjjg(0);
            for (int g = 0; g < group_tb.Rows.Count; g++)
            {
                TreeNode tn = new TreeNode();
                tn = treeView1.Nodes.Add(group_tb.Rows[g]["JGNAME"].ToString());
                tn.Text = group_tb.Rows[g]["jc"].ToString();
                tn.Tag = -1;
                tn.ToolTipText = "jg";
                tn.ImageIndex = 0;
                tn.SelectedImageIndex = 0;
                addBMTree(group_tb.Rows[g]["GRPUP_ID"].ToString(), "0", tn);
            }
            //外协单位
            TreeNode tn1 = new TreeNode();
            tn1 = treeView1.Nodes.Add("外协单位");
            tn1.Text = "外协单位";
            tn1.Tag = "0";
            tn1.ToolTipText = "jg";
            tn1.ImageIndex = 0;
            tn1.SelectedImageIndex = 0;
            tn1.Checked = true;
            addJGTree(group_tb.Rows[0]["GRPUP_ID"].ToString(), tn1);
            treeView1.Nodes[0].ExpandAll();
            treeView1.SelectedNode = treeView1.Nodes[0].NextVisibleNode;
            khTextBox.Focus();
        }

        /// <summary>
        /// 递归加载addJGTree列表
        /// </summary>
        /// <param name="fatherid">节点的fatherid</param>
        /// <param name="pnode">该节点</param>
        private void addJGTree(string fatherid, TreeNode pnode)
        {
            DataTable dt = group.GetDataBy_sjjg(int.Parse(fatherid)) ;
            DataView dvTree = new DataView(dt);
            dvTree.RowFilter = "[SJJG] = " + fatherid;
            foreach (DataRowView drv in dvTree)
            {
                TreeNode node = new TreeNode();
                node.ImageIndex = 1;
                node.SelectedImageIndex = 3;
                if (pnode == null)
                {
                    node.Text = drv["jc"].ToString();
                    node.Tag = drv["GRPUP_ID"].ToString();    //作为节点标识符
                    node.ToolTipText = "jg";
                    treeView1.Nodes.Add(node);
                    addJGTree(drv["GRPUP_ID"].ToString(), node);//递归  该节点加载子节点
                }
                else
                {
                    node.Text = drv["jc"].ToString();
                    node.Tag = drv["GRPUP_ID"].ToString();//作为节点标识符
                    node.ToolTipText = "jg";
                    pnode.Nodes.Add(node);
                    addJGTree(drv["GRPUP_ID"].ToString(), node);//递归  该节点加载子节点
                }
            }
        }

        /// <summary>
        /// 递归加载addBMTree列表
        /// </summary>
        /// <param name="fatherid">节点的fatherid</param>
        /// <param name="pnode">该节点</param>
        private void addBMTree(string jgid, string fatherid, TreeNode pnode)
        {
       DataTable dt = bm.GetDataBy_grpup_id(int.Parse(jgid));
          //  DataTable dt = bm.GetDataBy_oderBMMC(int.Parse(jgid));
            DataView dvTree = new DataView(dt);
            dvTree.RowFilter = "[SJBM] = " + fatherid;
            foreach (DataRowView drv in dvTree)
            {
                TreeNode node = new TreeNode();
                node.ImageIndex = 1;
                node.SelectedImageIndex = 3;
                if (pnode == null)
                {
                    node.Text = drv["BMMC"].ToString();
                    node.Tag = drv["DEPT_ID"].ToString();    //作为节点标识符
                    node.ToolTipText = "bm";
                    treeView1.Nodes.Add(node);
                    addBMTree(jgid, drv["DEPT_ID"].ToString(), node);//递归  该节点加载子节点
                }
                else
                {
                    node.Text = drv["BMMC"].ToString();
                    node.Tag = drv["DEPT_ID"].ToString();//作为节点标识符
                    node.ToolTipText = "bm";
                    pnode.Nodes.Add(node);
                    addBMTree(jgid, drv["DEPT_ID"].ToString(), node);//递归  该节点加载子节点
                }
            }
        }

        /// <summary>
        /// 树选中一结点时，在右侧的GridView中关联显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                int id = int.Parse(e.Node.Tag.ToString());
                string tooltiptext = e.Node.ToolTipText;

                if (tooltiptext.Equals("jg"))
                {
                    this.v_user_cardTableAdapter.FillBy_Allchild(this.dataSet1.V_user_card, int.Parse(treeView1.SelectedNode.Tag.ToString()));
                }
                else if (tooltiptext.Equals("bm"))
                {
                    this.v_user_cardTableAdapter.FillBy_DEPT_id(this.dataSet1.V_user_card, int.Parse(treeView1.SelectedNode.Tag.ToString()));
                }

                string sql = " 1=1 ";
                if (this.radioButton1.Checked == true)
                {
                    sql += "and CardId is NULL";
                }
                else
                {
                    sql += "and CardId is not NULL";
                }

                vusercardBindingSource.Filter = sql;
                if (vusercardBindingSource.Count < 1)
                {
                    pictureBox1.Image = global::kwzx.Properties.Resources.无图片;
                }
                //user_cardBindingSource_PositionChanged(sender, e); 
            }
        }

        /// <summary>
        /// 级联人员表及卡表信息显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void user_cardBindingSource_PositionChanged(object sender, EventArgs e)
        {
            if (vusercardBindingSource.Current != null)
            {
                groupBox5.Text = "人员信息查询   " + vusercardBindingSource.Count.ToString();
               
                string users_id = ((DataRowView)vusercardBindingSource.Current)["user_id"].ToString();
                string users_id9 = ((DataRowView)vusercardBindingSource.Current)["user_id"].ToString();
                string Imgpath = ((DataRowView)vusercardBindingSource.Current)["zp"].ToString(); ;
                if (!string.IsNullOrWhiteSpace(Imgpath))
                {
                    int x = Imgpath.IndexOf("ftp/") + 4;
                    string userImg = Imgpath.Substring(x, Imgpath.Length - x);   //ftp下载路径
                    // 路径为:DBFZSPersonImg/李瑞明131684197012105231.jpg
                    int userImginfo = userImg.IndexOf("/") + 1;
                    string spath = SPicUtils.path + "\\";
                    string zpname = users_id9 + ".dat";
                    string kkzp = FileTran.DownloadFile(spath, zpname, userImg);
                    // string imgname = userImg.Substring(userImginfo, (userImg.Length - userImginfo));
                    this.pictureBox1.Image = SPicUtils.PicConvert(kkzp);

                }
                else
                {
                    pictureBox1.Image = global::kwzx.Properties.Resources.无图片;
                }
                rybhTextBox.Text = ((DataRowView)vusercardBindingSource.Current)["rybh"].ToString();
                zSXMTextBox.Text = ((DataRowView)vusercardBindingSource.Current)["zsxm"].ToString();
                dEPT_idTextBox.Text = ((DataRowView)vusercardBindingSource.Current)["jc"].ToString();
                kh_textBox.Text = ((DataRowView)vusercardBindingSource.Current)["kh"].ToString();
                if (((DataRowView)vusercardBindingSource.Current)["uby"].ToString() == "-1")
                {
                    dEPT_idTextBox.Text = ((DataRowView)vusercardBindingSource.Current)["bmmc"].ToString();

                }
                dEPT_idTextBox.Text = dEPT_idTextBox.Text.Replace("(党委组织部)", "").Replace("(纪委办公室)", "");
                uBYTextBox.Text = ((DataRowView)vusercardBindingSource.Current)["gsbm"].ToString();
                gzTextBox.Text = ((DataRowView)vusercardBindingSource.Current)["gzmc"].ToString();
                gzTextBox.Text = gzTextBox.Text.Replace("（文秘、司机、厨师、保安、保洁、绿化）", "");
                xBTextBox.Text = ((DataRowView)vusercardBindingSource.Current)["xb"].ToString();
                zWTextBox.Text = ((DataRowView)vusercardBindingSource.Current)["zw"].ToString();
                dHTextBox.Text = ((DataRowView)vusercardBindingSource.Current)["dh"].ToString();
                sfzhTextBox.Text = ((DataRowView)vusercardBindingSource.Current)["sfzh"].ToString();

                string CardID = ((DataRowView)vusercardBindingSource.Current)["CardID"].ToString();

                // TODO: 这行代码将数据加载到表“dataSet1.K_Carddata”中。您可以根据需要移动或删除它。
                this.k_CarddataTableAdapter.FillBy_user_id(this.dataSet1.K_Carddata, Convert.ToInt32(users_id));
               
                string jgbm = ((DataRowView)vusercardBindingSource.Current)["jgbm"].ToString();
                if (jgbm == "000")
                {
                    cT_IDTextBox1.Text = "正式员工(蓝卡)";
                }
                else
                    if (jgbm == "999")
                    {
                        cT_IDTextBox1.Text = "访客(黄卡)";
                    }
                    else
                    {
                        cT_IDTextBox1.Text = "非正式员式(绿卡)";
                    }
                string CT_ID = "2";
                try
                {
                    CT_ID = cT_IDTextBox1.SelectedValue.ToString();
                }
                catch (Exception ex)
                {
                }
                //查询卡类型有效时间
                DataTable dtct = cd_card.GetDataBy_CT_ID(int.Parse(CT_ID));
                string CT_DefaultUseDate = "";
                string CT_Pressure = "0";
                string CT_UseDUD = "";
                string CT_Mark = "";
                if (dtct.Rows.Count > 0)
                {
                    CT_Pressure = dtct.Rows[0]["CT_Pressure"].ToString();
                    double k = double.Parse(CT_Pressure);
                    yjTextBox.Text = (Convert.ToInt32(k)).ToString();

                    CT_UseDUD = dtct.Rows[0]["CT_UseDUD"].ToString();
                    CT_Mark = dtct.Rows[0]["CT_Mark"].ToString();
                    CT_DefaultUseDate = dtct.Rows[0]["CT_DefaultUseDate"].ToString();
                    CT_Pressure = dtct.Rows[0]["CT_Pressure"].ToString();
                }
                //日期
                string fromdate = "";
                string to_date = "";
                if (CT_UseDUD == "False")
                {
                    fromdate = DateTime.Now.ToString(); ;
                    to_date = DateTime.Now.AddYears(30).ToString(); ;
                }
                else
                {
                    fromdate = DateTime.Now.ToString();
                    if (CT_Mark == "0")//日
                    {
                        double zq = double.Parse(CT_DefaultUseDate);
                        to_date = DateTime.Now.AddDays(zq).ToShortDateString();
                    }
                    if (CT_Mark == "1")//周
                    {
                        double zq = double.Parse(CT_DefaultUseDate) * 7;
                        to_date = DateTime.Now.AddDays(zq).ToShortDateString();
                    }
                    if (CT_Mark == "2")//月
                    {
                        int zq = int.Parse(CT_DefaultUseDate);
                        to_date = DateTime.Now.AddMonths(zq).ToShortDateString();
                    }
                    if (CT_Mark == "3")//年
                    {
                        int zq = int.Parse(CT_DefaultUseDate);
                        to_date = DateTime.Now.AddYears(zq).ToShortDateString();
                    }
                }
                fdateDateTimePicker.Text = fromdate;
                jdateDateTimePicker.Text = to_date;

                kztComboBox.Text = fkbk;
            }
            else
            {
                try
                {
                    rybhTextBox.Text = "";
                    zSXMTextBox.Text = "";
                    dEPT_idTextBox.Text = "";
                    uBYTextBox.Text = "";
                    gzTextBox.Text = "";
                    xBTextBox.Text = "";
                    zWTextBox.Text = "";
                    dHTextBox.Text = "";
                    sfzhTextBox.Text = "";
                    kh_textBox.Text = "";
                }
                catch (Exception ex)
                {
                }
            }
        }

        /// <summary>
        /// 搜索操作(查询功能)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            string sql = " 1=1 ";
            if (this.textBox1.Text.ToString() != "")
            {
                sql += " and ZSXM like '%" + this.textBox1.Text.ToString() + "%'";
            }
            if (this.textBox2.Text.ToString() != "")
            {
                sql += "and sfzh like '%" + this.textBox2.Text.ToString() + "%'";
            }
            if (this.textBox3.Text.ToString() != "")
            {
                sql += "and kh like '%" + this.textBox3.Text.ToString() + "%'";
            }
            if (this.radioButton1.Checked == true)
            {
                sql += "and CardId is NULL";
            }
            else
            {
                sql += "and CardId is not NULL";
            }
            vusercardBindingSource.Filter = sql;
            if (vusercardBindingSource.Count < 1)
            {
                pictureBox1.Image = global::kwzx.Properties.Resources.无图片;
            }
            user_cardBindingSource_PositionChanged(sender, e);
            this.user_cardDataGridView.Refresh();
        }

        private void radioButton_CheckedChanged(object sender, EventArgs e)
        {
            string sql = " 1=1 ";
            RadioButton rb = sender as RadioButton;
            if (rb.Name == "radioButton1")
            {
                sql += "and CardId is NULL";
                this.fkbutton.Enabled = true;
            }
            else if (rb.Name == "radioButton2")
            {
                sql += "and CardId is not NULL";
                this.fkbutton.Enabled = false;
            }

            vusercardBindingSource.Filter = sql;
            if (vusercardBindingSource.Count < 1)
            {
                pictureBox1.Image = global::kwzx.Properties.Resources.无图片;
            }
            user_cardBindingSource_PositionChanged(sender, e);
            this.user_cardDataGridView.Refresh();
        }

        private void DDSadd()
        {

        }

        /// <summary>
        /// 发卡
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void fkbutton_Click(object sender, EventArgs e)
        {
            if (vusercardBindingSource.Current == null)
            {
                MessageBox.Show("你没有选择发卡人！");
                return;
            }

            if (khTextBox.Text.Length > 10 || khTextBox.Text.Length < 10)
            {
                MessageBox.Show("卡号不正确！");
                return;
            }

            if (this.khTextBox.Text == "")
            {
                MessageBox.Show("未分配卡号，请先读取卡号！");
                return;
            }

            string kh = khTextBox.Text.Trim();
            DataSet1TableAdapters.K_CardTableAdapter kc = new DataSet1TableAdapters.K_CardTableAdapter();
            DataTable dtbl = kc.GetDataBy_kh(kh);
            if (dtbl.Rows.Count > 0)
            {
                MessageBox.Show("此卡号已分配过了(重复)");
                return;
            }
            int user_id = int.Parse(((DataRowView)vusercardBindingSource.Current)["user_id"].ToString());

            try
            {
                string CT_UseDUD = "";
                string CT_Mark = "";
                //  string CT_ID = ((DataRowView)user_crdBindingSource.Current)["CT_ID"].ToString();
                string CT_ID = cT_IDTextBox1.SelectedValue.ToString();
                //查询卡类型有效时间
                DataTable dtct = cd_card.GetDataBy_CT_ID(int.Parse(CT_ID));
                string CT_DefaultUseDate = "";
                string CT_Pressure = "0";
                if (dtct.Rows.Count > 0)
                {
                    CT_UseDUD = dtct.Rows[0]["CT_UseDUD"].ToString();
                    CT_Mark = dtct.Rows[0]["CT_Mark"].ToString();
                    CT_DefaultUseDate = dtct.Rows[0]["CT_DefaultUseDate"].ToString();
                    CT_Pressure = dtct.Rows[0]["CT_Pressure"].ToString();
                    // yjTextBox.Text = CT_Pressure;

                }
                ////日期
                string fromdate = "";
                string to_date = "";
                if (CT_UseDUD == "False")
                {
                    //正式员工无时间限止
                    fromdate = fdateDateTimePicker.Value.ToShortDateString();

                    to_date = jdateDateTimePicker.Value.ToShortDateString();
                }
                else
                {
                    fromdate = fdateDateTimePicker.Value.ToShortDateString();
                    to_date = jdateDateTimePicker.Value.ToShortDateString();
                }

                //superma数据更新   获取人员的身份证号，去施普玛库是查询该人是否存在。不存在，提示用户人员未同步，不能发卡。
                string user_sfzh = ((DataRowView)vusercardBindingSource.Current)["sfzh"].ToString();
                DataTable super_user_dt = tb_user.GetDataBy_sfzh(user_sfzh);
                int super_user_dt_count = super_user_dt.Rows.Count;
                if (super_user_dt_count < 1)
                {
                    MessageBox.Show("施普玛中无此人员信息，请先同步该人员后，方可配卡！");
                    return;
                }
                else if (super_user_dt_count > 1)
                {
                    MessageBox.Show("施普玛中此人员信息存在多条，请确认该人员后，方可配卡！");
                    return;
                }

                //卡表插入一条记录(更新插入语句，加入部分字段)
                decimal yj = 0;
                int login_user_id = 0;
                login_user_id = Convert.ToInt32(kwzx.Utils.CurrentUser.userid);                
                yj = decimal.Parse(CT_Pressure);
                object kcardid = k_card.InsertQuery(user_id, int.Parse(CT_ID), khTextBox.Text, sMTextBox.Text.ToString(), null, Convert.ToDateTime(fromdate), Convert.ToDateTime(to_date), fkbk, 0, yj, login_user_id, null, null, null, null);
                //以前的插入语句
                //object kcardid = k_card.InsertQuery1(user_id, int.Parse(CT_ID), khTextBox.Text, "", Convert.ToDateTime(fromdate), Convert.ToDateTime(to_date), fkbk, 0);

                khTextBox.Text = "";
                string CardID_dv = kcardid.ToString();//返回插入记录的ID                

                string CardtypeID2 = ((DataRowView)vusercardBindingSource.Current)["sfzh"].ToString();
                int CD_CardType = Convert.ToInt32(cT_IDTextBox1.SelectedValue.ToString());

                string SM = sMTextBox.Text;
                int SXH = 0;
                DateTime czrq = DateTime.Now;
                string kzt = fkbk;
                string sh = "0";
                decimal thje = 0;
                string lrz = Utils.CurrentUser.xm;
                int xfzt = 0;
                DateTime zzrq = DateTime.Parse(jdateDateTimePicker.Value.ToString());


                //K_Carddata，k_deviceIssue各插入一条记录
                kcad.Insert(user_id, CardtypeID2, CD_CardType, kh, SM, SXH, czrq, kzt, sh, thje, lrz, xfzt, zzrq);
                k_deviceIssue.InsertQuery(kh, "0", DateTime.Now, "K_Card", CardID_dv.ToString(), kzt, "");

                if (kzt == "挂失")
                {
                    k_card.UpdateQuery_CardID(k_gs_id);
                }

                //superma数据更新
                //把卡号写入superma  仅有一条记录的时候，更新人员的卡号进去
                if (super_user_dt_count == 1)
                {
                    int spm_user_id = int.Parse(super_user_dt.Rows[0]["nUserIdn"].ToString());
                    DateTime utcNow = DateTime.Now.AddHours(8);
                    double utc = ConvertDateTimeInt(utcNow);

                    //代替页面上“取消发卡”功能里对施普玛软件的操作，在发卡时，删除旧卡号，配上新卡号
                    //这里要查询一下发卡记录表，看看sup_suer_id的人员信息在tb_user_card表中是否存在多条（>=1），在nLatest字段为1的记录
                    //若有的话，就要新增一条删除的记录，之后在配上一张发行卡
                    DataTable dtuser = tb_user_card.GetDataBy_nUserIdn_and_nLatest_1(spm_user_id);
                    if (dtuser.Rows.Count >= 1)
                    {
                        for (int i = 0; i < dtuser.Rows.Count; i++)
                        {
                            //TB_USER_CARD表数据例子
                            //8508	6215	2	2386104800	0	0	1382372898	0	0	1	0   发行卡
                            //8566	6215	1	2386104800	0	0	1382378937	0	0	2	0   删除卡
                            //8567	6215	1	0	        0	0	1382378937	0	0	1	0   零卡
                            //8568	6215	2	2386104800	0	0	1382378952	0	0	1	1   发行卡

                            //7199	8186	1	2670532624	0	0	1376408597	0	0	1	0   注册卡
                            //7986	8186	1	2670532624	0	0	1381940449	0	0	2	0   删除卡
                            //7987	8186	1	0	        0	0	1381940449	0	0	1	0   零卡
                            //7988	8186	2	2670532624	0	0	1381940472	0	0	1	1   发行卡
                            
                            //获取卡ID
                            int old_nCardIdn = int.Parse(dtuser.Rows[i]["nCardIdn"].ToString());
                            //获取卡号
                            string old_sCardNo = dtuser.Rows[i]["sCardNo"].ToString();

                            //修改之前的卡设置nLatest字段为"0"
                            tb_user_card.UpdateQuery_nCardIdnIs0(old_nCardIdn);
                            //新增一条删除旧卡记录
                            tb_user_card.Insert(spm_user_id, 1, old_sCardNo, "0", 0, Convert.ToInt32(utc), 0, 0, 2, 0);
                            //重新配一张卡号为零的卡
                            tb_user_card.Insert(spm_user_id, 1, "0", "0", 0, Convert.ToInt32(utc), 0, 0, 1, 0);
                        }
                    }
                    //配一张新卡
                    tb_user_card.Insert(spm_user_id, 2, kh, "0", 0, Convert.ToInt32(utc), 0, 0, 1, 1);
                }


               //添加权限
                //18全部生产区通行   20全部生产区(除中控中化)             
                useraccg.InsertQuery(20, user_id);

                //DDS数据更新
                string pcname_dds = Properties.Settings.Default.pcname_dds.ToString();
                string sfzh = ((DataRowView)vusercardBindingSource.Current)["sfzh"].ToString();
                string zSXM = ((DataRowView)vusercardBindingSource.Current)["zSXM"].ToString();
                string BMMC = ((DataRowView)vusercardBindingSource.Current)["BMMC"].ToString();

                //查询卡类型有效时间
                // DataTable dtct=  cd_card.GetDataBy_CT_UseDUD();

                Spread sp = new Spread();
                sp.StartConnect();
                sp.useradd(pcname_dds, sfzh, kh, zSXM, user_id.ToString(), BMMC, fromdate, to_date, "发卡");
                sp.DesInit();
                khTextBox.Focus();
                // MessageBox.Show(kzt+"成功！");
                if (this.treeView1.SelectedNode.ToolTipText.Equals("jg"))
                {
                    this.v_user_cardTableAdapter.FillBy_Allchild(this.dataSet1.V_user_card, Convert.ToInt32(treeView1.SelectedNode.Tag.ToString()));

                }
                else if (treeView1.SelectedNode.ToolTipText.Equals("bm"))
                {
                    this.v_user_cardTableAdapter.FillBy_DEPT_id(this.dataSet1.V_user_card, Convert.ToInt32(treeView1.SelectedNode.Tag.ToString()));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public double ConvertDateTimeInt(System.DateTime time)
        {
            double intResult = 0;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            intResult = (time - startTime).TotalSeconds;
            return intResult;
        }
        public DateTime ConvertIntDatetime(double utc)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            startTime = startTime.AddSeconds(utc);
            startTime = startTime.AddHours(8);//转化为北京时间(北京时间=UTC时间+8小时 )
            return startTime;
        }

        private void gbbutton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 挂失
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            //卡片表K_Card  卡状态（挂失） kzt 挂失卡号ID gsk_CardID is not null and gsk_CardID=""

            int user_id = int.Parse(((DataRowView)vusercardBindingSource.Current)["user_id"].ToString());
            //查询挂失人员信息
            DataTable kdt = k_card.GetDataBy_gs_BK("挂失", user_id);
            if (kdt.Rows.Count > 0)
            {
                k_gs_id = Convert.ToInt32(kdt.Rows[0]["CardID"].ToString());
                fkbk = "发卡";
                fkbutton_Click(sender, e);
                k_card.DeleteQuery(k_gs_id);
            }
            else
            {
                MessageBox.Show("没有挂失数据，不能补办卡片");
            }
        }

        /// <summary>
        /// 测试DDS
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            Spread sp = new Spread();
            sp.StartConnect();
            string message = "<perform><cmd>DisplayMessage</cmd><param><query><Param1> Hi, How are you? </Param1></query></param></perform>";
            string pcname = Properties.Settings.Default.pcname_dds;
            sp.SpreadSend(pcname, message);
            sp.DesInit();
            //DataTable tb = k_card.GetData();

            //for (int i = 0; i < tb.Rows.Count; i++)
            //{
            //    string xcCardID = tb.Rows[i]["CardID"].ToString();
            //    string xckh = tb.Rows[i]["kh"].ToString();
            //    if (xckh != "")
            //    {
            //        k_deviceIssue.InsertQuery(xckh, "0", DateTime.Now, "K_Card", xcCardID, "发卡", "");
            //    }
            //}
        }

        /// <summary>
        /// 卡片打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string username1 = zSXMTextBox.Text;
            string bh1 = rybhTextBox.Text;
            string bm1 = uBYTextBox.Text;
            string jg1 = dEPT_idTextBox.Text;
            string lj1 = "";
            Image img1 = pictureBox1.Image;
            if (uBYTextBox.Text == "")
            {
                jg1 = uBYTextBox.Text;
                bm1 = dEPT_idTextBox.Text;
            }

            ZXPSampleCode.frmMultiPrint frmmu = new ZXPSampleCode.frmMultiPrint("", username1, bh1, bm1, jg1, lj1, img1);
            frmmu.ShowDialog();
        }

        /// <summary>
        /// 补录人员进DDS操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            v_user_cardTableAdapter.Fill(this.dataSet1.V_user_card);

            kwzx.DataSet1TableAdapters.V_user_cardTableAdapter v_user_card_adp = new DataSet1TableAdapters.V_user_cardTableAdapter();

            DataTable dt_v_user_card = v_user_card_adp.GetData();
            for (int i = 0; i < dt_v_user_card.Rows.Count; i++)
            {
                //if (i >= 9)
                //{
                //    return;
                //}
                //DDS数据更新
                string pcname_dds = Properties.Settings.Default.pcname_dds.ToString();
                string sfzh = dt_v_user_card.Rows[i]["sfzh"].ToString();
                string kh = dt_v_user_card.Rows[i]["kh"].ToString();
                string zSXM = dt_v_user_card.Rows[i]["zSXM"].ToString();
                string user_id = dt_v_user_card.Rows[i]["user_id"].ToString(); 
                string BMMC = dt_v_user_card.Rows[i]["BMMC"].ToString(); 
                string fromdate = dt_v_user_card.Rows[i]["zSXM"].ToString(); 
                string to_date= dt_v_user_card.Rows[i]["zSXM"].ToString(); 

                //查询卡类型有效时间
                // DataTable dtct=  cd_card.GetDataBy_CT_UseDUD();

                Spread sp = new Spread();
                sp.StartConnect();
                sp.useradd(pcname_dds, sfzh, kh, zSXM, user_id, BMMC, fromdate, to_date, "发卡");
                sp.DesInit();
            }            
        }

        private void button6_Click(object sender, EventArgs e)
        {
            string  ZSXM =  ((DataRowView)vusercardBindingSource.Current)["ZSXM"].ToString();
            DialogResult dr = MessageBox.Show("是否取消【" + ZSXM + "】的发卡？", "取消提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == DialogResult.Yes)
            {
               
                

                int CardID = int.Parse(((DataRowView)vusercardBindingSource.Current)["CardID"].ToString());
                kwzx.DataSet1TableAdapters.K_CardTableAdapter kc = new DataSet1TableAdapters.K_CardTableAdapter();
                kc.DeleteQuery(CardID);
                int user_id = int.Parse(((DataRowView)vusercardBindingSource.Current)["user_id"].ToString());

                k_deviceIssue.InsertQuery("", "0", DateTime.Now, "T_USER", user_id.ToString(), "退卡", "");
                if (this.treeView1.SelectedNode.ToolTipText.Equals("jg"))
                {
                    this.v_user_cardTableAdapter.FillBy_Allchild(this.dataSet1.V_user_card, Convert.ToInt32(treeView1.SelectedNode.Tag.ToString()));

                }
                else if (treeView1.SelectedNode.ToolTipText.Equals("bm"))
                {
                    this.v_user_cardTableAdapter.FillBy_DEPT_id(this.dataSet1.V_user_card, Convert.ToInt32(treeView1.SelectedNode.Tag.ToString()));
                }
            }
        }

        private void fk_Activated(object sender, EventArgs e)
        {
            khTextBox.Focus();
        }

        private void button7_Click(object sender, EventArgs e)
        {

            for (int i = 0; i < user_cardDataGridView.Rows.Count; i++)
            {
                DataSet2TableAdapters.K_CardTableAdapter kc = new DataSet2TableAdapters.K_CardTableAdapter();
                string CardID = user_cardDataGridView.Rows[i].Cells["CardID"].Value.ToString();
              string name = user_cardDataGridView.Rows[i].Cells["dataGridViewTextBoxColumn4"].Value.ToString();

              string xckh = user_cardDataGridView.Rows[i].Cells["dataGridViewTextBoxColumn26"].Value.ToString();
                if(name.Contains("访客"))
                {
                kc.UpdateQuery(DateTime.Parse("2013-10-1"), DateTime.Parse("2014-6-1"), int.Parse(CardID));
                k_deviceIssue.InsertQuery(xckh, "0", DateTime.Now, "K_Card", CardID, "授权", "");
                }
            }
        }
    }
}
